﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sherwood.Content.Tasks;
using Xtensive.Storage;

namespace Sherwood.Content.DO.Model
{
    [HierarchyRoot]
    [Serializable]
    public abstract class Task : Entity, ITask
    {
        protected Task()
            : this(DateTime.UtcNow)
        {
        }

        protected Task(DateTime? plannedDate)
        {
            PlannedDate = plannedDate;
        }

        [Field, Key]
        public Guid Id { get; private set; }

        [Field]
        public DateTime? FailedDate { get; private set; }

        [Field]
        public DateTime? PlannedDate { get; set; }

        [Field]
        public DateTime? ExecutedDate { get; set; }

        [Field(Length = Int32.MaxValue)]
        public string Exception { get; private set; }

        public abstract void Execute();

        public virtual void OnExecutionFinished(Exception exception)
        {
            FailedDate = exception == null ? new DateTime?() : DateTime.UtcNow;
            Exception = exception == null ? null : exception.ToString();

            if (exception != null)
                OnExecutionFailed(exception);
            else
                ExecutedDate = DateTime.UtcNow;
        }

        protected virtual void OnExecutionFailed(Exception exception)
        {
            // we take the task out of the queue by default

            PlannedDate = exception is ReprocessableException
                              ? (DateTime?) DateTime.UtcNow.AddSeconds(5)
                              : null;
        }
    }
}
